package com.cqhfan.common.autoconfigure.mvc;

import com.cqhfan.common.autoconfigure.mvc.properties.AuthProperties;
import com.cqhfan.common.autoconfigure.mvc.properties.SecurityProperties;
import com.cqhfan.common.interceptors.LoginInterceptor;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.config.annotation.InterceptorRegistration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * @author 眭传洪
 * @create 2024-11-14 19:59
 */
@Configuration
@RequiredArgsConstructor
public class WebMvcConfig implements WebMvcConfigurer {

    private final AuthProperties authProperties;

    private final SecurityProperties securityProperties;

    private final StringRedisTemplate stringRedisTemplate;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 不需要拦截 直接放行
        if (!authProperties.getEnabled()) {
            return;
        }

        // 注册拦截器
        InterceptorRegistration registration = registry
                .addInterceptor(new LoginInterceptor(stringRedisTemplate, securityProperties.getPublicKey()))
                .order(Integer.MIN_VALUE);

        // 添加不拦截路径
        registration.excludePathPatterns(authProperties.getExcludePaths());
        // 添加swagger路径
        registration.excludePathPatterns(
                "/v2/**",
                "/v3/**",
                "/swagger-resources/**",
                "/webjars/**",
                "/doc.html",
                "/favicon.ico",
                "/error"
        );
    }
}
